<template>
  <table class="cart" border="1">
    <caption>
      购物车
    </caption>
    <tr>
      <th>全选 <input type="checkbox" v-model="state" /></th>
      <th>商品</th>
      <th>单价</th>
      <th>数量</th>
      <th>小计</th>
      <th>操作</th>
    </tr>
    <tr v-for="item in list" :key="item.id" class="item">
      <th><input type="checkbox" v-model="item.isSelected" /></th>
      <th>
        <div class="product">
          <img
            :src="getImages(item.productCover)"
            alt=""
            class="product-cover"
          />
          <span class="product-info">{{ item.productInfo }}</span>
        </div>
      </th>
      <th>{{ item.productPrice }}</th>
      <th><input type="number" min="1" v-model="item.num" /></th>
      <th>¥{{ item.num * item.productPrice }}</th>
      <th><button @click="handelDel(index)">删除</button></th>
    </tr>
    <tr>
      <th colspan="6" align="left">总价:¥{{ totalPrice }}</th>
    </tr>
  </table>
</template>
<script setup>
import { computed, onMounted, ref } from 'vue'
import { getData } from './api/getData'
const list = ref([])
onMounted(() => {
  getCommodityListHttp()
})
function getCommodityListHttp() {
  getData('http://39.103.151.139:8000/cart').then((res) => {
    list.value = res.map((item) => {
      return {
        isSelected: item.isSelected,
        productCover: item.productCover,
        productName: item.productName,
        productPrice: item.productPrice,
        num: 1,
      }
    })
  })
}
function getImages(_url) {
  if (_url !== undefined) {
    let _u = _url.substring(7)
    return 'https://images.weserv.nl/?url=' + _u
  }
}
function handelDel(index) {
  list.value.splice(index, 1)
}
const totalPrice = computed(() => {
  return list.value
    .filter((item) => item.isSelected == true)
    .reduce((total, item) => {
      return total + item.productPrice * item.num
    }, 0)
})
const state = computed({
  get: () => {
    return list.value.every((item) => item.isSelected)
  },
  set: (val) => {
    list.value.forEach((item) => {
      item.isSelected = val
    })
  },
})
</script>
<style scoped>
.cart {
  width: 800px;
  margin: 100px auto;
  border-collapse: collapse;
}

.product {
  display: flex;
  gap: 10px;
  align-items: center;
}
.product .product-cover {
  width: 100px;
  height: 150px;
}
</style>
